﻿using SheepStorage.Domain.Entity;
using SheepStorage.Repository.BaseImp;
using SheepStorage.Repository.Interface;
using System.Reflection;
using Module = Autofac.Module;
namespace SheepStorage.API.Baseclass
{
	public static class RegisterRepositories
	{

		public static void RegisterRepositoriess(this IServiceCollection services)
		{
			var entityTypes = new List<Type>
	{
		typeof(SheepChangeDormitory), // 其他实体类...
        // 例如 typeof(YourTableName), typeof(MenuRolePermission), ...
    };
			// 定义所有仓储接口的列表
			var repositoryInterfaces = entityTypes
				.Select(entityType => typeof(IBaseRepository<>).MakeGenericType(entityType))
				.ToList();


			// 获取所有实现了 IBaseRepository<T> 的仓储类
			var repositoryImplementations = Assembly.GetAssembly(typeof(BaseRepository<>))
				.GetTypes()
				.Where(type => type.IsClass && !type.IsAbstract &&
							  type.GetInterfaces().Any(i => i.IsGenericType &&
															  i.GetGenericTypeDefinition() == typeof(IBaseRepository<>)))
				.ToList();

			// 循环注册每个仓储接口及其实现
			foreach (var repoInterface in repositoryInterfaces)
			{
				// 找到对应的仓储实现
				var implementationType = repositoryImplementations
					.FirstOrDefault(impl => impl.GetInterfaces().Any(i => i == repoInterface));

				if (implementationType != null)
				{
					// 注册到服务容器
					services.AddScoped(repoInterface, implementationType);
				}
				else
				{
					throw new InvalidOperationException($"No implementation found for {repoInterface.FullName}");
				}
			}


				//// 获取所有实现了 IBaseRepository<T> 的类型
				//var repositoryInterfaceTypes = Assembly.GetAssembly(typeof(IBaseRepository<>))
				//	.GetTypes()
				//	.Where(type => type.IsClass && type.IsGenericType &&
				//				  type.GetInterface("IBaseRepository`1") != null);

				//foreach (var repositoryInterfaceType in repositoryInterfaceTypes)
				//{
				//	// 获取 T 的类型参数
				//	var entityType = repositoryInterfaceType.GetGenericArguments()[0];

				//	// 动态创建实现类型的实例
				//	var repositoryImplementationType = typeof(BaseRepository<>).MakeGenericType(entityType);

				//	// 注册到服务容器
				//	services.AddScoped(repositoryInterfaceType, repositoryImplementationType);
				//}
			}


		public static void RegisterServices(this IServiceCollection services)
		{
			// 获取所有服务接口和它们的实现
			var serviceTypes = Assembly.GetExecutingAssembly().GetTypes()
				.Where(type => type.IsClass && !type.IsAbstract
					&& type.GetInterfaces().Any(i => i.IsInterface))
				.ToList();

			// 遍历并注册每个服务
			foreach (var serviceType in serviceTypes)
			{
				// 接口类型
				var interfaceType = serviceType.GetInterfaces().First();

				// 注册到服务容器
				services.AddScoped(interfaceType, serviceType);
			}
		}


	}

}










